package com.slothought.rowgazer


class ParamsExtractor{
	private Map params;
	
	ParamsExtractor(Map params){
		this.params = params
	}
	
	public Request getRequest(){
        def paramVs = params.findAll{ key, value -> key ==~ /^d[0-9]+[.]v[0-9]+$/ }
        def paramCs = params.findAll{ key, value -> key ==~ /^c[0-9]+$/ }
        def paramT = params['t']
        
        Map<String> argVs = paramVs.inject([:]){ result, entry -> 
          
          def key = entry.getKey()
          def value = entry.getValue()
          def tmp = key.split("[.]")

          def d = Integer.parseInt(tmp[0].replace("d", ""))
          def v = Integer.parseInt(tmp[1].replace("v", ""))
         
          if (result[(d)] == null){
              result[(d)] = [ (v) : value ]
          }
          else{
              result[(d)][(v)] = value
          }
          return result
        }


        Map<String> argCs = paramCs.inject([:]){result, entry ->
           def key = entry.getKey()
           def value = entry.getValue()
           def c = Integer.parseInt(key.replace("c", ""))
           
           result[(c)] = value
           return result
        }

        String argT = paramT;
        Request request = null;
        if (!(argT == null || argCs == null || argVs == null)){
        	request = new Request(argT, argCs, argVs);
        }
        return request;
	}

	public SchemaInfo getSchemaInfo(){
		def paramS = params['s'];
		DbSchema dbSchema = DbSchema.findByName(paramS);
		
		return new SchemaInfo(
					dataSourceConfigName:	dbSchema.dataSourceConfig.name,
					jdbcCatalog:	dbSchema.jdbcCatalog,
					jdbcSchema:  	dbSchema.jdbcSchema,
					isStaticCatalog: dbSchema.isStaticCatalog,
					isStaticSchema: dbSchema.isStaticSchema
				)
		
	}
	
}
